package com.bigteddy.BankMark;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class PrimeActivity extends Activity {
	TextView text;
	TextProgressBar prog;
	Button but;
	EditText begin, end;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.prime);
		but = (Button) findViewById(R.id.prime_start);
		prog = (TextProgressBar) findViewById(R.id.prime_progress);
		prog.setTextSize(20);

		text = (TextView) findViewById(R.id.prime_result);

		begin = (EditText) findViewById(R.id.prime_min);
		end = (EditText) findViewById(R.id.prime_max);

		but.setOnClickListener(new AdapterView.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				but.setEnabled(false);
				new CalcPrimeTask().execute(
						Integer.parseInt(begin.getText().toString()),
						Integer.parseInt(end.getText().toString()));
			}
		});
	}

	class CalcPrimeTask extends AsyncTask<Integer, Integer, String> {
		@Override
		protected void onPostExecute(String result) {
			text.setText(result);
			prog.setText("Done!");
			but.setEnabled(true);
		}

		@Override
		protected void onPreExecute() {
			System.gc();

		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			prog.setMax(values[0]);
			prog.setProgress(values[1]);
			prog.setText("Calculated " + values[1] + ". iteration!");
		}

		@Override
		protected String doInBackground(Integer... arg0) {
			int primes = 0, limit = arg0[1], start = arg0[0];
			StringBuilder builder = new StringBuilder();
			long then = SystemClock.elapsedRealtime();
			for (int i = start; i <= limit; i++) {
				if (i > 1) {
					int pater = 0;
					for (int j = 1; j <= i; j++) {
						int mater = i % j;
						if (mater == 0)
							pater++;
					}
					if (pater == 2) {
						primes++;
						builder.append(i + "; ");
					}
				}
				publishProgress(arg0[1], i);
			}
			long elapsed = SystemClock.elapsedRealtime() - then;
			String old = builder.toString();
			builder.delete(0, builder.length());
			builder.append("The actual data you want:\n");
			builder.append("Elapsed Time: " + elapsed + "ms!" + "\n\nPrimes ("
					+ primes + "):\n" + old);

			return builder.toString();
		}
	}
}
